package com.fenfen.novel.rest;

import android.content.Context;

import com.fenfen.novel.utils.CommonUtil;

import java.io.File;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

public class RestClient {

  private Retrofit retrofit;

  private volatile static RestClient instance;

  private RestClient(Context context) {
//    Gson gson = new GsonBuilder()
//        .setDateFormat("yyyy-MM-dd HH:mm:ss")
//        .create();

//    ObjectMapper mapper = new ObjectMapper();
//    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    File path = context.getExternalCacheDir();
    File httpCacheDirectory = new File(path, "requests");
    if (!httpCacheDirectory.isDirectory() || !httpCacheDirectory.exists()) {
      httpCacheDirectory.mkdirs();
    }
    CachingControlInterceptor cacheIntercepter = new CachingControlInterceptor(context);
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(cacheIntercepter)
        .addInterceptor(interceptor)
        .cache(new Cache(httpCacheDirectory, 10 * 1024 * 1024))
        .build();

    retrofit = new Retrofit.Builder()
        .baseUrl(CommonUtil.BASE_URL)
        .client(client)
//        .addConverterFactory(JacksonConverterFactory.create(mapper))
        .addConverterFactory(FastJsonConverterFactory.create())
        .build();
  }

  public static void init(Context context) {
    if (instance == null) {
      synchronized (RestClient.class) {
        if (instance == null) {
          instance = new RestClient(context);
        }
      }
    }
  }

  public static RestClient newInstance() {
    if (instance == null) {
      throw new NullPointerException("you should call init() first");
    }
    return instance;
  }

  public <T> T invokeService(Class<T> clz) {
    return retrofit.create(clz);
  }

  public NovelService getNovelService() {
    return invokeService(NovelService.class);
  }

}
